package org.mspring.mlog.web.module.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.entity.Post;
import org.mspring.mlog.entity.constants.CacheNames;
import org.mspring.mlog.entity.constants.PageNames;
import org.mspring.mlog.service.PostService;
import org.mspring.mlog.service.StatisticService;
import org.mspring.platform.cache.Cache;
import org.mspring.platform.cache.CacheManager;
import org.mspring.platform.dao.Order.OrderType;
import org.mspring.platform.dao.Page;
import org.mspring.platform.dao.query.QueryBuilder;
import org.mspring.platform.web.freemarker.FreemarkerVariableNames;
import org.mspring.platform.web.freemarker.widget.stereotype.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author Gao Youbo
 * @since 2012-7-23
 */
@Action
public class Web_IndexWidget extends Web_AbstractWidget {

    private PostService postService;
    private StatisticService statisticService;
    private CacheManager cacheManager;
    private Cache indexPostListCache;

    /**
     *
     * 文章首页
     *
     * @param postPage
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping({ "/", "" })
    public String index(HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<Post> postPage = new Page<>();
        postPage.setPageNo(1);
        Page<Post> cached = indexPostListCache.get(String.valueOf(postPage.getPageNo()));
        if (cached != null) {
            postPage = cached;
        } else {
            postPage.addOrder("createTime", OrderType.DESC);
            QueryBuilder queryBuilder = QueryBuilder.instance(Post.class).buildValuedEqual("status", Post.Status.PUBLISH);
            postPage = postService.listPage(queryBuilder, postPage);
            indexPostListCache.set(String.valueOf(postPage.getPageNo()), postPage);
        }
        model.addAttribute(FreemarkerVariableNames.POST_PAGE, postPage);
        setCurrnetPage(model, PageNames.INDEX);

        // 站点访问量+1
        statisticService.siteClick();
        return "skin:/index";
    }

    @Autowired
    public void setPostService(PostService postService) {
        this.postService = postService;
    }

    @Autowired
    public void setStatisticService(StatisticService statisticService) {
        this.statisticService = statisticService;
    }

    @Autowired
    public void setCacheManager(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
        this.indexPostListCache = this.cacheManager.getCache(CacheNames.INDEX_POST_LIST_CACHE);
    }

}
